//
//  UITextView+ZDTextView.m
//  OCSinaWeiBo
//
//  Created by Apple on 15/11/8.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "UITextView+Extension.h"
#import "ZDTextAttachment.h"


@implementation UITextView (Extension)

///textView插入emoji表情
- (void)insertEmojiWith:(ZDEmoji *)emoji
{
    if (!emoji)
    {
        return;
    }
    
    //点击的是删除按钮  删除
    if (emoji.removeBtn)
    {
        [self deleteBackward];
        
        return;   //一定要return  否则会看到删除后 光标不移动的bug
    }
    
    //插入emoji表情(本质上就是字符串)
    if (emoji.emojiString)
    {
        [self insertText:emoji.emojiString];
        
        return;
    }
    
    //插入表情图片(图片不能通过insertText插入)
    //创建附件
    ZDTextAttachment *attachment = [[ZDTextAttachment alloc] init];
    //给附件添加图片
    attachment.image = emoji.emojiImage;
    attachment.name = emoji.chs;
    
    //根据文本的高度调整附件图片的bounds
    CGFloat height = self.font.lineHeight;
    attachment.bounds = CGRectMake(0, -height * 0.2, height, height);
    
    //创建带附件的属性文本
    NSAttributedString *attributeStr = [NSAttributedString attributedStringWithAttachment:attachment];
    
    //获取textView的属性文本  转换为可变 属性文本
    NSMutableAttributedString *attributeStrM = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    
    //获取当前选中的范围
    NSRange range = self.selectedRange;
    
    //替换选中的文本
    [attributeStrM replaceCharactersInRange:range withAttributedString:attributeStr];
    
    //为属性文本添加字体
    [attributeStrM addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(range.location, attributeStr.length)];
    
    //重新赋值给textView的属性文本
    self.attributedText = attributeStrM;
    
    //调整光标的位置 到插入属性文本的后面
    self.selectedRange = NSMakeRange(range.location + 1, 0);
    
    //由于插入表情图片不会触发通知 这里选择手动发出通知UITextViewTextDidChangeNotification
    [[NSNotificationCenter defaultCenter] postNotificationName:UITextViewTextDidChangeNotification object:self];
}


- (NSString *)emojiText
{
    NSAttributedString *attributeStr = self.attributedText;
    
    NSMutableString *text = [NSMutableString string];
    
    [attributeStr enumerateAttributesInRange:NSMakeRange(0, attributeStr.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
        
        ZDTextAttachment *attachment = attrs[@"NSAttachment"];
        
        if (attachment)   //有表情图片 拿到表情图片对应的字段拼接
        {
            [text appendString:attachment.name];
        }
        else
        {   //没有表情图片 直接取出遍历出来的子字符串拼接
            NSString *subStr = [attributeStr.string substringWithRange:range];
            
            [text appendString:subStr];
        }
    }];
    
    return text;
}

@end
